package com.baidu.ueditor.upload;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.UEditorConfig;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Uploader {
    private HttpServletRequest request = null;
    private Map<String, Object> conf = null;

    public Uploader(HttpServletRequest request, Map<String, Object> conf) {
        this.request = request;
        this.conf = conf;
    }

    public final State doExec() {
        State state = null;

        if (!ServletFileUpload.isMultipartContent(request)) {
            return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
        }

        long maxSize = ((Long) conf.get("maxSize")).longValue();
        //访问路径后缀
        String returnPath = (String) conf.get("savePath");

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        if (items!=null){
            for (FileItem item : items) {
                if (item.isFormField()) {
                    continue;
                }
                String fileName = item.getName();
                String suffix = FileType.getSuffixByFilename(fileName);
                if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
                    return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
                }

                fileName = fileName.substring(0,
                        fileName.length() - suffix.length());
                returnPath = returnPath + suffix;

                returnPath = PathFormat.parse(returnPath, fileName);

                //物理保存路径
                String savePath = UEditorConfig.getGLOBAL_SAVE_PATH_PREFFIX() + returnPath;

//                    InputStream is = file.getInputStream();
                State storageState = StorageManager.saveFile(item,savePath, maxSize);

//                    is.close();
                if (storageState.isSuccess()) {
                    storageState.putInfo("url", PathFormat.format(returnPath));
                    storageState.putInfo("type", suffix);
                    storageState.putInfo("original", fileName + suffix);
                }
                state = storageState;
            }
        }



       /* StandardMultipartHttpServletRequest multipartRequest = (StandardMultipartHttpServletRequest) request;
        MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();
        Set<String> keys = map.keySet();
        try {
            for (String key : keys) {
                List<MultipartFile> list = map.get(key);
                for (MultipartFile file : list) {
                    String originFileName = file.getOriginalFilename();
                    String suffix = FileType.getSuffixByFilename(originFileName);
                    if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
                        return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
                    }
                    originFileName = originFileName.substring(0,
                            originFileName.length() - suffix.length());
                    returnPath = returnPath + suffix;

                    returnPath = PathFormat.parse(returnPath, originFileName);

                    //物理保存路径
                    String savePath = UEditorConfig.getGLOBAL_SAVE_PATH_PREFFIX() + returnPath;

//                    InputStream is = file.getInputStream();
                    State storageState = StorageManager.saveFile(file,savePath, maxSize);

//                    is.close();
                    if (storageState.isSuccess()) {
                        storageState.putInfo("url", PathFormat.format(returnPath));
                        storageState.putInfo("type", suffix);
                        storageState.putInfo("original", originFileName + suffix);
                    }
                    state = storageState;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            state = new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
        }*/

        return state;
    }

    private static boolean validType(String type, String[] allowTypes) {
        List<String> list = Arrays.asList(allowTypes);
        return list.contains(type);
    }
}
